package com.leyou.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.dto.SpecGroupDTO;
import com.leyou.dto.SpecParamDTO;
import com.leyou.mapper.SpecGroupMapper;
import com.leyou.mapper.SpecParamMapper;
import com.leyou.pojo.SpecGroup;
import com.leyou.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServcie {
    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroupDTO> queryGroupByCid(Long cid) {
        //查询规格组
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(cid);
        List<SpecGroup> list = specGroupMapper.select(specGroup);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException((ExceptionEnum.SPEC_NOT_FOUND));
        }
        //对象转换
        return BeanHelper.copyWithCollection(list, SpecGroupDTO.class);


    }

    public List<SpecParamDTO> querySpecParamByGid(Long gid, Long cid, Boolean searching) {
        //gid和cid必选一个
        if (gid == null && cid == null && searching == null) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //查询条件
        SpecParam specParam = new SpecParam();
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);
        List<SpecParam> list = specParamMapper.select(specParam);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SpecParamDTO.class);
    }

    public List<SpecGroupDTO> querySpecs(Long id) {
        //1.查询规格组
        List<SpecGroupDTO> specGroupDTOList = queryGroupByCid(id);
        //优化:
        //2.查询分类下的所有规格参数
        List<SpecParamDTO> specParams = querySpecParamByGid(null, id, null);
        //3.判断哪些参数属于哪个组?需要根据groupId对specParams分组,id一致的，放到一个集合
        //可以得到一个map:Map<Long,List<SpecParamDT)>>
        //Long:分组id
        Map<Long, List<SpecParamDTO>> map = specParams.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //4.放入group
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            List<SpecParamDTO> specParamDTOS = map.get(specGroupDTO.getId());
            specGroupDTO.setParams(specParamDTOS);
        }



 /*       //2.查询组内参数
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            Long groupId = specGroupDTO.getId();
            //根据组id查询组内参数
            List<SpecParamDTO> specParamDTOList = querySpecParamByGid(groupId, null, null);
            specGroupDTO.setParams(specParamDTOList);

        }*/
        return specGroupDTOList;
    }
}
